﻿package org.net.socket
{
	import org.net.DMsg.*;
	import org.net.UMsg.*;
	
	import flash.events.EventDispatcher;
	import flash.events.ProgressEvent;
	import flash.net.Socket;
	import flash.utils.ByteArray;
	
	import org.abcFrame.core.*
	import org.enmu.*
	import flash.errors.*
	import flash.events.*
	
	public class Connection extends EventDispatcher
	{
			private var _socket:Socket;

			//因为有可能一个完整的包会经过多次网络连接传过来，因此要将当前读到的内容缓存，直到可以组成一个完整包
			private var _buf:ByteArray = new ByteArray();
			
			/** 连接服务器*/
			public function Connection(host:String,port:int)
			{
				var a:DMsg11;
				var a2:DMsg12;
				var a3:DMsg13;
				var a4:DMsg14;
				var a5:DMsg15;
				var a6:DMsg16;
				var a21:DMsg21;
				var a22:DMsg22;
				var a23:DMsg23;
				var a24:DMsg24;
				
				/*
				var data:ByteArray = new ByteArray();
				data.writeUTF("abc");
				data.position = 0;
				var  dmsg:DMsg = DMsg.parse(data,11);
				trace(dmsg);
				*/
	
				_socket = new Socket();
				_socket.addEventListener(ProgressEvent.SOCKET_DATA, onData);
				
				_socket.addEventListener(Event.CLOSE, closeHandler);
                _socket.addEventListener(Event.CONNECT, connectHandler);
                _socket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
                _socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);

				_socket.connect(host,port);
				//TODO 这里应该需要请求session id
			}
			
			/**发送*/
			public function send(msg:UMsg):void
			{
				_socket.writeBytes(msg.toBytes());
				_socket.flush();
			}
			
			private function onData(event:ProgressEvent):void
			{
				_socket.readBytes(_buf,0,_socket.bytesAvailable);
				_buf.position = 0;
				
				while( _buf.bytesAvailable > 4)
				{
					//协议号
					var type:int = _buf.readShort();
					//数据正文长度
					var dataLen:int = _buf.readShort();
					if( _buf.bytesAvailable  >= dataLen )//含完整的数据包
					{
						var data:ByteArray = new ByteArray();
						_buf.readBytes(data,0,dataLen);
						var  dmsg:DMsg = DMsg.parse(data,type);
						AbcEventDispatcher.instance.dispatcher(AbcEventType.socketMessage,dmsg)
						
					}else
					{
						_buf.position-=4;
						break;
					}
				}
				
				if(_buf.position!= 0){
					var newBuf:ByteArray = new ByteArray();
					if(_buf.position < _buf.length)
					{
						_buf.writeBytes(newBuf,_buf.position,_buf.bytesAvailable);
					}
					_buf = newBuf;
				}			
			}
	
			function closeHandler(e:Event) { AbcEventDispatcher.instance.dispatcher(AbcEventType.socketConnectFailed,e) }

			function connectHandler(e:Event) { AbcEventDispatcher.instance.dispatcher(AbcEventType.socketConnectSuccess,e) }
			
			function ioErrorHandler(e:IOErrorEvent) { AbcEventDispatcher.instance.dispatcher(AbcEventType.socketConnectFailed,e) }
			
			function securityErrorHandler(e:SecurityErrorEvent) { AbcEventDispatcher.instance.dispatcher(AbcEventType.socketConnectFailed,e)}
			
	}
}